package com.biz.service.MService.goods;

import com.biz.model.Hmodel.base.TBaseUser;
import com.biz.model.Hmodel.base.TBaseUserIntegral;
import com.biz.model.Hmodel.base.TWxGoods;
import com.biz.model.Hmodel.goods.TBaseWxgoods;
import com.biz.model.Hmodel.order.TOrderDetail;
import com.biz.model.Hmodel.order.TOrderMain;
import com.biz.model.Pmodel.base.PWxGoods;
import com.biz.model.Pmodel.base.PbasePics;
import com.biz.model.Pmodel.order.PorderDetail;
import com.biz.model.common.MessageBox;
import com.biz.service.HService.base.BaseServiceImpl;
import com.biz.utils.UuidUtil;
import com.framework.dao.hdao.BaseDaoI;
import com.framework.dao.mdao.DaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author lzq
 */
@Service("goodsService")
public class GoodsServiceImpl extends BaseServiceImpl<TWxGoods> implements GoodsServiceI {
	@Resource(name = "daoSupport")
	private DaoSupport dao;

	@Autowired
	private BaseDaoI<TBaseUser> tBaseUserDao;

	@Autowired
	private BaseDaoI<TOrderMain> tOrderMainDao;

    @Autowired
    private BaseDaoI<TOrderDetail> tOrderDetailDao;

    @Autowired
    private BaseDaoI<TBaseUserIntegral> tBaseUserIntegralDao;

    @Autowired
    private BaseDaoI<TBaseWxgoods> tBaseWxgoodsDao;


	@Override
	public List<PWxGoods> getGoodsList() throws Exception{

		return (List<PWxGoods>)dao.findForList("GoodsDao.getGoodsList",null);
	}

	@Override
	public PWxGoods getGoodsDetialById(String goodsId) throws Exception{

		return (PWxGoods)dao.findForObject("GoodsDao.getGoodsDetialById",goodsId);
	}

	@Override
	public List<PbasePics> getPicsByGoodsList(String goodsId)throws Exception{

		return (List<PbasePics>)dao.findForList("GoodsDao.getPicsByGoodsList",goodsId);
	}

	@Override
	public synchronized MessageBox doCharge(String goodsId, String userId)
	{
		MessageBox box = new MessageBox();
		box.setMsg("兑换失败！");
		box.setSuccess(false);
		try {
			//开始兑换
			//获取商品信息
            TBaseWxgoods tBaseWxgoods = tBaseWxgoodsDao.getById(TBaseWxgoods.class,goodsId);
			if(tBaseWxgoods != null && tBaseWxgoods.getPrice() != null)
			{
			    int integralNeed = tBaseWxgoods.getPrice().intValue();
                //获取个人信息
                TBaseUser tBaseUser = tBaseUserDao.getById(TBaseUser.class, userId);
                //验证积分
                if(tBaseUser!=null && tBaseUser.getIntegralNow() !=null
                        && tBaseUser.getIntegralNow().intValue() >= integralNeed)
                {
                    int integralNow = tBaseUser.getIntegralNow().intValue() - integralNeed;
                    String code = getRndNumCode();
                    //生成订单(主单)
                    String mainId = saveOrderMain(userId, integralNeed, code);
                    //子单
                    saveDetail(goodsId, integralNeed, mainId);
                    //插入积分记录
                    saveIntgeralSheet(userId, integralNeed, mainId);
                    //修改个人积分
                    tBaseUser.setIntegralNow(Double.valueOf(integralNow));
                    tBaseUserDao.update(tBaseUser);
                    //更新销量
                    tBaseWxgoods.setSales(1 + tBaseWxgoods.getSales());
                    tBaseWxgoodsDao.update(tBaseWxgoods);
                    //结束
                    box.setMsg("兑换成功！");
                    box.setCode(code);
                    box.setSuccess(true);
                }else{
                    box.setMsg("当前可兑换积分不足，无法兑换！");
                    box.setSuccess(false);
                    return box;
                }
            }else{
                box.setMsg("商品不存在！");
                box.setSuccess(false);
                return box;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return box;
	}

    private void saveIntgeralSheet(String userId, int integralNeed, String mainId) {
        TBaseUserIntegral tBaseUserIntegral = new TBaseUserIntegral();
        tBaseUserIntegral.setId(UuidUtil.get32UUID());
        tBaseUserIntegral.setIntegral(integralNeed);
        tBaseUserIntegral.setSource(1);
        tBaseUserIntegral.setSourceId(mainId);
        tBaseUserIntegral.setUserId(userId);
        tBaseUserIntegral.setSourceMsg("积分商城兑换商品消耗积分");
        tBaseUserIntegral.setIsdel(0);
        tBaseUserIntegral.setCreateTime(new Date());
        tBaseUserIntegral.setType(1);//消耗积分
        tBaseUserIntegralDao.save(tBaseUserIntegral);
    }

    private void saveDetail(String goodsId, int integralNeed, String mainId) {
        TOrderDetail tOrderDetail = new TOrderDetail();
        tOrderDetail.setId(UuidUtil.get32UUID());
        tOrderDetail.setGoodsId(goodsId);
        tOrderDetail.setCount(1);
        tOrderDetail.setState((short)1);
        tOrderDetail.setIsdel((short)1);
        tOrderDetail.setOrderId(mainId);
        tOrderDetail.setPrice(Double.valueOf(integralNeed));
        tOrderDetail.setGoodsTotal(Double.valueOf(integralNeed));
        tOrderDetail.setCreateTime(new Date());
        tOrderDetailDao.save(tOrderDetail);
    }

    private String saveOrderMain(String userId, int integralNeed, String code) {
        TOrderMain tOrderMain = new TOrderMain();
        tOrderMain.setBuyUserId(userId);
        tOrderMain.setGoodsTotal(Double.valueOf(integralNeed));
        tOrderMain.setPayTotal(Double.valueOf(integralNeed));
        tOrderMain.setCreateTime(new Date());
        tOrderMain.setCode(code);
        tOrderMain.setState((short)1);
        tOrderMain.setIsdel((short)0);
        tOrderMain.setId(UuidUtil.get32UUID());
        tOrderMain.setIsClosed((short)0);
        tOrderMainDao.save(tOrderMain);
        return tOrderMain.getId();
    }


    public String getRndNumCode()
    {
        Random rand = new Random();
        Date now = new Date();
        long t = now.getTime();
        long  rndCode = Long.valueOf(t * 1000L + (long)rand.nextInt(1000));
        return String.valueOf(rndCode);
    }

    @Override
    public boolean testUserOrdersByUserIdAndCode(String userId, String code){
        boolean flag = false;
        try {
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("code",code);
            Integer count = (Integer)dao.findForObject("GoodsDao.getUserOrderCount",map);
            if(count.intValue() == 1)
            {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;

    }

    @Override
    public List<Map<String,Object>> getChargeHistory(String userId)throws Exception{

        return (List<Map<String,Object>>)dao.findForList("GoodsDao.getChargeHistory",userId);
    }

    @Override
    public PorderDetail getOrderDetailByCode(String detailId)throws Exception
    {
        return (PorderDetail)dao.findForObject("GoodsDao.getOrderDetailByCode",detailId);
    }
}
